package com.ebupt.migu.music.commons.selfdom.demo.impl;

import com.ebupt.migu.globalpopup.entity.ConditionRelation;
import com.ebupt.migu.globalpopup.enums.ConditionEnum;
import com.ebupt.migu.music.commons.selfdom.demo.DynamicGroup;
import com.ebupt.migu.music.commons.selfdom.demo.impl.identifier.AbstractIdentifierImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 动态人群子条件实现类
 *
 * @author lemon
 * @since 2022-06-09 11:40
 */
@Slf4j
public class DynamicGroupImpl extends AbstractIdentifierImpl implements DynamicGroup {

    /**
     * idfa异常值
     */
    public static final String IDFA_ERROR_VALUE = "00000000-0000-0000-0000-000000000000";

    @Override
    public boolean getDynamicGroup(Map data, ConditionRelation conditionRelation) {
        log.info("条件配置信息：{}", conditionRelation.toString());
        LinkedHashMap<Boolean, Integer> booleanIntegerMap = new LinkedHashMap<>();

        // uid
        Object uidObject = data.get(ConditionEnum.getKeyValue(2, 1));
        // 手机号
        Object msisdnObject = data.get(ConditionEnum.getKeyValue(2, 2));
        // IMEI/IDFA
        Object idfaObject = data.get(ConditionEnum.getKeyValue(1, 4));
        boolean uidBoolean = uidObject == null || "".equals(uidObject);
        boolean msisdnBoolean = msisdnObject == null || "".equals(msisdnObject);
        boolean idfaBoolean = idfaObject == null || "".equals(idfaObject);
        if (uidBoolean && msisdnBoolean && idfaBoolean) {
            booleanIntegerMap.put(false, conditionRelation.getCConnector());
        } else {
            if (!uidBoolean) {
                String uid = uidObject.toString();
                boolean b = super.userGroupEqualTo(uid, conditionRelation.getGroupId());
                booleanIntegerMap.put(b, conditionRelation.getCConnector());
            }
            if (!msisdnBoolean) {
                String msisdn = msisdnObject.toString();
                boolean b = super.userGroupEqualTo(msisdn, conditionRelation.getGroupId());
                booleanIntegerMap.put(b, conditionRelation.getCConnector());
            }
            if (!idfaBoolean) {
                String idfa = idfaObject.toString();
                if (!IDFA_ERROR_VALUE.equals(idfa)) {
                    boolean b = super.userGroupEqualTo(idfa, conditionRelation.getGroupId());
                    booleanIntegerMap.put(b, conditionRelation.getCConnector());
                } else {
                    booleanIntegerMap.put(false, conditionRelation.getCConnector());
                }
            }
        }
        return super.getRelation(booleanIntegerMap);
    }
}